#include "XnccThread.h"
#include <pthread.h>

#include "PlatLogger.h"
#include "Util.h"

namespace xncc {
namespace foundation {
    PThread::PThread(ThreadFunc func, std::string name, types::thread_id_t tid, int coreId)
        : func_(std::move(func)), name_(std::move(name)), id_(tid), coreId_(coreId)
    {
    }
    PThread::~PThread() = default;

    void PThread::start() { t_ = std::thread(&PThread::runInThread, this); }

    void PThread::join()
    {
        if (t_.joinable()) {
            t_.join();
        }
    }

    void PThread::runInThread()
    {
        if (coreId_ != -1) {
            if (shared::CommonBusi::setCpuAffinity(coreId_) != 0) {
                TRACE_ERROR << ("thread bind core failed");
            }
        }
        if (!name_.empty()) {
            pthread_setname_np(pthread_self(), name_.c_str());
        }
        if (func_) {
            func_();
        }
        else {
            TRACE_ERROR << ("thread func not init");
        }
    }
}  // namespace foundation
}  // namespace xncc